package com.example.jxauflea.service.impl;

import com.example.jxauflea.mapper.*;
import com.example.jxauflea.pojo.*;
import com.example.jxauflea.service.PayService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class PayServiceImpl implements PayService {


    @Autowired
    private PayOrderMapper payOrderMapper;

    @Autowired
    private ShopCarMapper shopCarMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsImgMapper goodsImgMapper;

    @Override
    @Transactional
    public void userPay(PayOrderPO payOrderPO) {

        // 清理购物车
        //shopCarMapper.cleanByUserIdAndGoodId(payOrderPO.getUserId(),payOrderPO.getGoodsId());

        // order表中添加相应的数据(用户买入，商家用户卖出数据)
        OrderPO orderPO=new OrderPO();
        orderPO.setUuid(UUID.randomUUID().toString());
        orderPO.setUserIdBuy(payOrderPO.getUserId());
        orderPO.setGoodsId(payOrderPO.getGoodsId());
        orderMapper.indesrtBuyOrderPO(orderPO);

        // 下架商品(更新商品的状态和商品的数量)
        // goodsMapper.soldGood(payOrderPO.getGoodsId());
        GoodsPO goodsPO=new GoodsPO();
        goodsPO.setQuantity(payOrderPO.getQuantity());
        goodsPO.setUuid(payOrderPO.getGoodsId());
        goodsMapper.updateGoods(goodsPO);

        // 查询出卖家的id
        String sellerId= goodsMapper.getUserId(payOrderPO.getGoodsId());

        // 添加卖家信息到order表中
        OrderPO orderPO1=new OrderPO();
        orderPO1.setUuid(UUID.randomUUID().toString());
        orderPO1.setUserIdSell(sellerId);
        orderPO1.setGoodsId(payOrderPO.getGoodsId());
        orderMapper.saveOrderUserSell(orderPO1);

        // 发票数据
        payOrderMapper.insertPayOrderPO(payOrderPO);
    }

    @Override
    public List<PayOrderVO> getPayOrder(String userId) {
        List<PayOrderVO> payOrderVOS = payOrderMapper.selectByUserId(userId);
        for (PayOrderVO payOrderVO : payOrderVOS) {
            // 循环查询出商品图品并进行赋值操作
            List<String> imgUrlList = goodsImgMapper.selectByGoodsId(payOrderVO.getGoodsId());// 返回一个图片集合但是可以选择一张作为展示图片
            payOrderVO.setImgUrls(imgUrlList);
            init(payOrderVO);
        }
        return payOrderVOS;
    }

    @Override
    public void deletePayOrder(PayOrderPO payOrderPO) {

        payOrderMapper.deletePayOrder(payOrderPO);
    }

    public void init(PayOrderVO payOrderVO) {
        Date createTime = payOrderVO.getCreateTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(createTime);
        payOrderVO.setTime(format);
    }
}
